# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  
  include AuthenticatedSystem
  
  rescue_from Facebooker::Session::SessionExpired, :with => :facebook_session_expired

  def facebook_session_expired
    clear_fb_cookies!
    clear_facebook_session_information
    reset_session # remove your cookies!
    flash[:error] = "Your facebook session has expired."
    redirect_to root_url
  end
  
  
  helper :all # include all helpers, all the time
  before_filter :set_facebook_session
  
  helper_method :facebook_session
  
  helper_method :is_admin?
  
  before_filter :set_locale
  
  before_filter :set_location
  
  def is_admin? 
      if logged_in? && current_user.login == "roma"
        true
      else
        false
      end
  end
    
  def admin_required
    is_admin? || admin_denied
  end
    
  def admin_denied
    respond_to do |format|
      format.html do
        store_location
        flash[:notice] = 'You must be an admin to do that.'
        #redirect_to forums_path
      end
    end
  end 
  
  protect_from_forgery # See ActionController::RequestForgeryProtection for details
  
  
  def auto_complete_for_location
    city_names = ""
    if params[:q].to_s != ""
      city_geo = GeoKit::Geocoders::GoogleGeocoder.geocode(params[:q])
      cities = city_geo.lat ? [city_geo] : []
      cities += Location.find(:all, 
                              :conditions => ["full_address != ? AND full_address like ? ",
                                              city_geo.lat ? city_geo.full_address : "", params[:q] + "%"],
                              :limit => 12)
      cities.each { |i| city_names += i.full_address + "|" + (i.class == Location ? i.id.to_s : "") + "\n" }
    end
    render :text => city_names
  end
  
  # Scrub sensitive parameters from your log
  # filter_parameter_logging :password
  
  protected
  
  def set_locale
    session[:locale] = params[:locale] if params[:locale]
    I18n.locale = session[:locale] || I18n.default_locale
    locale_path = "#{LOCALES_DIRECTORY}#{I18n.locale}.yml"
    unless I18n.load_path.include? locale_path
      I18n.load_path << locale_path
      I18n.backend.send(:init_translations)
    end
  rescue Exception => err
    logger.error err
    flash.now[:notice] = "#{I18n.locale} translation not available"
    I18n.load_path -= [locale_path]
    I18n.locale = session[:locale] = I18n.default_locale
  end

  def set_location    
    unless (session[:location] and session[:location].lat)
      l = GeoKit::Geocoders::IpGeocoder.geocode(request.remote_ip)      
      session[:location] = GeoKit::Geocoders::GoogleGeocoder.geocode(l.lng ? l.city.to_s + ", " + l.country : "New York, United States")      
    end
    @user_location = session[:location]
  end
  
end
